package com.LeeCode;

import org.junit.jupiter.api.Test;

import java.util.PriorityQueue;
import java.util.Stack;

/**
 * 最小栈
 */

public class Code155 {

    @Test
    public void test() {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.getMin());
        minStack.pop();
        System.out.println(minStack.top());
        System.out.println(minStack.getMin());
    }
}


class MinStack {
    class Node {
        int val;
        Node next;

        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }
    }

    private Stack<Integer> stack;
    private Node dummyHead;
    private Node dummyTail;

    public MinStack() {
        stack = new Stack<>();
        dummyHead = new Node();
        dummyTail = new Node();
        dummyHead.next = dummyTail;
    }

    public void push(int val) {
        stack.push(val);
        insert(val);
    }

    public void pop() {
        Integer num = stack.pop();
        remove(num);
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return dummyHead.next.val;
    }

    private void insert(int val) {
        Node pre = dummyHead;
        while (pre.next != dummyTail && pre.next.val < val) {
            pre = pre.next;
        }
        Node node = new Node(val);
        node.next = pre.next;
        pre.next = node;
    }

    private void remove(int val) {
        Node pre = dummyHead;
        while (pre.next.val != val) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
    }
}